package com.jy.shorturl.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jy.shorturl.dao.ShortUrlDao;
import com.jy.shorturl.service.ShortUrlService;
import com.jy.shorturl.util.SourceUrlIsLegal;

@Service
@Transactional
public class ShortUrlServiceImpl implements ShortUrlService {
	
	@Value("${URL}")
	private String url;
	
	@Autowired
	private ShortUrlDao sud;

	@Override
	public void insertShortUrl(String shortUrl) {
		// TODO Auto-generated method stub
		sud.insertShortUrl(shortUrl);
	}

	@Override
	public String insertSourceUrlWhithShortUrl(String shortUrl,String sourceUrl) {
		String str = sud.selectShortUrlIsBeUsed(shortUrl);
		String str1 = sud.selectSourceUrl(sourceUrl);
		if("N".equals(SourceUrlIsLegal.IsLegeal(sourceUrl)))
		return "此源链接不合法或不存在";
		if(str != null)
		return "此短链接已被使用";
		if(str1 != null)
		return "此源连接已被使用，短链接地址为:"+url+sud.selectShortUrlBySourceUrl(sourceUrl);
		
		try {
			sud.updateSourceUrlWhithShortUrl(shortUrl, sourceUrl,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "系统错误";
		}
		return url+shortUrl;
	}

	@Override
	public String insertSourceUrlWhithShortUrlOParm(String sourceUrl) {
		String str1 = sud.selectSourceUrl(sourceUrl);
		String str2 = sud.selectShortUrlNotUsed();
		if("N".equals(SourceUrlIsLegal.IsLegeal(sourceUrl)))
		return "此源链接不合法或不存在";
		if(str1 != null)
		return "此源连接已被使用，短链接地址为:"+url+sud.selectShortUrlBySourceUrl(sourceUrl);
		
		try {
			sud.updateSourceUrlWhithShortUrl(str2, sourceUrl,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "系统错误";
		}
		
		return url+str2;
	}

	@Override
	public String selectShortUrlUrlBySource(String shortUrl) {
		// TODO Auto-generated method stub
		return sud.selectSourceUrlByShortUrl(shortUrl);
	}

}
